﻿using System;
using System.Collections.Generic;
using Microsoft.Exchange.Data.Transport;
using Microsoft.Exchange.Data.Transport.Email;
using Microsoft.Exchange.Data.Transport.Smtp;
using Microsoft.Exchange.Data.Transport.Routing;
using Microsoft.Exchange.Data.Mime;


namespace SaveRecipient
{
    public class SaveRecipientFactory : RoutingAgentFactory
    {
        public override RoutingAgent CreateAgent(SmtpServer server)
        {
            RoutingAgent ra = new SaveOriginalRecipientAgent();
            return ra;
        }
    }
}

public class SaveOriginalRecipientAgent : RoutingAgent
{
    public SaveOriginalRecipientAgent()
    {
        base.OnSubmittedMessage += new SubmittedMessageEventHandler(SaveOriginalRecipientAgent_OnSubmittedMessage);
    }

    void SaveOriginalRecipientAgent_OnSubmittedMessage(SubmittedMessageEventSource esEvtsource, QueuedMessageEventArgs qm)
    {

        EmailMessage em = qm.MailItem.Message;
        List<string> recipients = new List<string>();

            foreach (EmailRecipient er in em.To)
            {
                recipients.Add(er.SmtpAddress.ToLower());
            }

            //If desired, also check CC 

            foreach (EmailRecipient er in em.Cc)
            {
                recipients.Add(er.SmtpAddress.ToLower());
            }

            MimeDocument mime = qm.MailItem.Message.MimeDocument;
            HeaderList HeaderList = mime.RootPart.Headers;
            MimeNode mimeNode = HeaderList.LastChild;

            string originalRecipients = string.Join(";", recipients.ToArray());

            TextHeader recipientAddressHeader = new TextHeader("X-OriginalRecipientAddress", originalRecipients);
            HeaderList.InsertBefore(recipientAddressHeader, mimeNode);

    }
}
